<template>
  <div class="box-main1">
    <div class="box-header2">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/admin/index' }"
          >控制台</el-breadcrumb-item
        >
        <el-breadcrumb-item>班级信息</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- <slot :data="data"></slot> -->
    <div class="box-main2">
      <div class="box-search2">
        <div class="box-input2" style="width: 180px">
          <el-input
            @keydown.enter.native="clkBtnSearch"
            @clear="clkBtnSearch"
            clearable
            size="mini"
            v-model="searchInfo.searchKey"
            placeholder="班级名称"
          ></el-input>
        </div>
        <div class="box-input2">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-search"
            @click="clkBtnSearch"
            >搜索</el-button
          >
          <el-button
            size="mini"
            type="warning"
            icon="el-icon-plus"
            @click="clkBtnAdd"
            >新增</el-button
          >
        </div>
      </div>

      <div class="box-content2">
        <div class="box-table2">
          <el-table
            class="tbl1"
            :data="classesPage.list"
            :stripe="true"
            size="small"
          >
            <el-table-column
              type="index"
              :index="(classesPage.pageNum - 1) * classesPage.pageSize + 1"
              label="序号"
              width="180"
            ></el-table-column>
            <el-table-column label="班级名称" width="220">
              <template slot-scope="scope">
                <span>{{ scope.row.class_name }}</span>
              </template>
            </el-table-column>
            <el-table-column label="班级状态" width="222">
              <template slot-scope="scope">
                <span>{{ scope.row.class_state | filterState }}</span>
              </template>
            </el-table-column>
            <el-table-column label="验证码" width="220">
              <template slot-scope="scope">
                <span>{{ scope.row.class_code }}</span>
              </template>
            </el-table-column>
            <el-table-column label="创建日期" width="220">
              <template slot-scope="scope">
                <span>{{ scope.row.create_date }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
              <template slot-scope="scope">
                <span>
                  <el-button
                    type="primary"
                    size="mini"
                    @click="clkBtnShowAddStudent(scope.row)"
                    >学生</el-button
                  >
                  <el-button
                    type="primary"
                    size="mini"
                    @click="clkBtnEdit(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    type="warning"
                    size="mini"
                    @click="clkBtnDelete(scope.row)"
                    >删除</el-button
                  >
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="box-page2">
          <el-pagination
            layout="prev, pager, next"
            :total="classesPage.total"
            :current-page="classesPage.pageNum"
            :page-size="classesPage.pageSize"
            @current-change="chgCurrPage"
          >
          </el-pagination>
        </div>
      </div>
      <el-card class="box-card" v-if="showStudentsDialog">
        <div slot="header" class="clearfix">
          <span>{{ className[1] }}</span>
          <el-button
            style="float: right; padding: 3px 0"
            type="text"
            @click="closeCard"
            >关闭</el-button
          >
        </div>
        <div v-for="o in nowClassStu" :key="o.noid" class="text item">
          <div class="cardCon">
            <span>{{ o.student_realname }}申请加入班级</span>
          </div>
          <div class="cardTime">
            <span>{{ o.join_time }}</span>
          </div>
          <div class="cardCaoZuo">
            <el-button size="mini" @click="tongyi(o)">同意</el-button>
            <el-button size="mini" @click="jujue(o)">拒绝</el-button>
          </div>
        </div>
      </el-card>
      <!-- <el-dialog
        title="选择学生"
        class="dialog1"
        :show-close="false"
        :close-on-click-modal="false"
        :visible.sync="showStudentsDialog"
      >
        <el-transfer
          filterable
          filter-placeholder="请输入学生姓名"
          v-model="currentStudents"
          :titles="className"
          @change="handleChange"
          :data="generateData"
          ref="transferCom"
        >
        </el-transfer>
        <span slot="footer" class="dialog-footer">
          <el-button size="mini" type="primary" @click="saveStudent"
            >确 定</el-button
          >
          <el-button size="mini" @click="clearTransferData">取 消</el-button>
        </span>
      </el-dialog> -->
    </div>

    <el-dialog
      title="新增班级"
      class="dialog1"
      :show-close="false"
      :close-on-click-modal="false"
      :visible.sync="showSaveteClassesDialog"
    >
      <div>
        <div class="box-content2">
          <div class="box-table2" style="width: 420px">
            <el-form
              size="mini"
              ref="classes"
              :model="classes"
              label-width="120px"
            >
              <el-form-item label="班级名称">
                <el-input v-model="classes.class_name"></el-input>
              </el-form-item>
              <el-form-item label="班级状态" v-if="addOrEdit === 'edit'">
                <el-radio-group v-model="classes.class_state">
                  <el-radio :label="1">在授</el-radio>
                  <el-radio :label="0">结业</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="clkBtnSave"
          >确 定</el-button
        >
        <el-button size="mini" @click="showSaveteClassesDialog = false"
          >取 消</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import request from '@/common/utils/request';

export default {
  computed: {
    loginUserInfo () {
      return this.$store.state.loginUserInfo;
    },

  },
  data () {
    return {
      searchInfo: { searchKey: null },
      classesPage: { pageNum: 1, pageSize: 12, list: [] },

      pageLoading: false,

      showSaveteClassesDialog: false,
      showStudentsDialog: false,

      data: "",

      classes: {},
      studentGroupList: [],
      radio: "1",
      nowStudenList: [],
      studentList: [],
      studentNameList: [],
      studentNoidList: [],
      className: ['学生列表', '大数据2104A班'],
      generateData: [],
      currentStudents: [],
      studentsNoid: [],
      classStuInfo: [],
      addOrEdit: null,
      nowClassStu: [],
      classRow: null,
    };
  },
  // mounted () {
  //   this.loadStudentGroupList();
  //   this.loadStudentList();
  //   this.getList();
  //   this.getNowStu();
  // },
  watch: {
    $route: {
      handler: function (to, from) {
        if (to.path == '/admin/classes_list') {
          this._initData();
        }
      }, immediate: true
    },
    //   // lambda 语法
    //   handler: (newVal,oldVal) =>{
    //     if(newVal.path == '/student_group/list'){
    //
    //     }
    //   }, immediate: true
  },
  methods: {
    _initData () {
      this.loadStudentGroupList();
      this.loadStudentList();
      this.getList();
      // setTimeout(() => {
      //   this.getNowStu();
      // }, 1000)
    },

    clkBtnSearch () {
      this.getList();
    },
    createGenerateData () {
      // this.studentList.forEach((item, index) => {
      //   this.studentNameList[index] = item.student_realname;
      //   this.studentNoidList[index] = item.noid;
      // })
      const generateData = _ => {
        const data = [];
        const students = this.studentList;
        students.forEach((student, index) => {
          data.push({
            label: student.student_realname,
            key: student.noid,
          });
        });
        return data;
      };
      this.generateData = generateData();
      // console.log(this.generateData);
    },
    clkBtnShowAddStudent (row) {
      this.classRow = row
      let url1 = this.settings.apiUrl + '/classes/getUserInfoJoinClassMessageByClassesId';
      let d1 = { 'class_code': row.class_code }
      this.className[1] = row.class_name;
      this.className[2] = row.noid;
      this.showStudentsDialog = true;
      this.loadCurrentStudents(row);
      request.post(url1, d1).then((d1r) => {
        console.log(d1r);
        this.nowClassStu = d1r.data
      })

    },
    loadCurrentStudents (row) {
      let url1 = this.settings.apiUrl + '/classes/currentStudents';
      let d1 = { 'class_noid': row.noid };
      request.post(url1, d1).then((d1r) => {
        if (d1r.code === 0) {
          this.currentStudents = [];
          if (d1r.data.length != 0) {
            for (let i = 0; i < d1r.data.length; i++) {
              this.$set(this.currentStudents, i, d1r.data[i].student_noid);
            }
          } else {
            this.currentStudents = [];
          }
        }
      })
    },
    loadStudentList () {//获取全部学生
      let url1 = this.settings.apiUrl + '/student/list';
      let d1 = {};

      request.post(url1, d1).then((d1r) => {
        if (d1r.code === 0) {
          this.studentList = d1r.data;
          this.createGenerateData();
        }
      })
    },
    loadStudentGroupList () {
      let url1 = this.settings.apiUrl + '/student_group/list';
      let d1 = {};

      request.post(url1, d1).then((d1r) => {
        if (d1r.code === 0) {
          this.studentGroupList = d1r.data;
        }
      })
    },
    getNowStu () {
      let url1 = this.settings.apiUrl + '/classes/currentStudents';
      this.classStuInfo.forEach(item => {
        item.stuList = []
        request.post(url1, { 'class_noid': item.id }).then((d1r) => {
          if (d1r.code === 0) {
            // console.log(d1r);
            this.studentList.forEach(ite => {
              d1r.data.forEach(it => {
                if (ite.noid === it.student_noid) {
                  ite.classNoId = item.id
                  if (item.id === ite.classNoId) {
                    item.stuList.push(ite.student_realname)
                  }
                }
              })
            })
          }
        })
      })

    },
    getList () {
      let url1 = this.settings.apiUrl + '/classes/page';
      let d1 = {};
      d1.pageNum = this.classesPage.pageNum;
      d1.pageSize = this.classesPage.pageSize;

      d1.searchKey = this.searchInfo.searchKey;
      request.post(url1, d1).then((d1r) => {
        this.pageLoading = false;
        if (d1r.code === 0) {
          // console.log(d1r);
          this.classesPage = d1r.data;
          d1r.data.list.forEach(item => {
            this.classStuInfo.push({
              id: item.noid,
              stuList: []
            })
          })
          setTimeout(() => {
            this.getNowStu()
          }, 500)
          // console.log(this.classNoId);
        } else {

          this.$alert('获取班级信息失败：' + d1r.msg, '提示', {
            type: 'warning'
          });

        }
      }).catch(err => {
        this.pageLoading = false;
      });
    },
    // 点击新增用户的按钮
    clkBtnAdd () {
      this.classes = {};
      this.showSaveteClassesDialog = true;
      this.addOrEdit = 'add'
    },
    clkBtnEdit (row) {
      this.classes = JSON.parse(JSON.stringify(row));
      this.showSaveteClassesDialog = true;
      this.addOrEdit = 'edit'
    },
    saveStudent () {
      let url1 = this.settings.apiUrl + '/classes/saveStudents';
      let d1 = { noid: this.className[2], studentsNoid: this.studentsNoid };
      // console.log(this.studentsNoid);
      request.post(url1, d1).then((d1r) => {
        if (d1r.code === 0) {
          this.$alert("添加成功~");
          this.getList();
        } else {
          this.$alert("由于未知原因，添加失败！")
        }
      }).catch(err => {
        this.loading = false;
        console.log(err);
      });
      this.showStudentsDialog = false;
    },
    clearTransferData () {
      const { transferCom } = this.$refs;
      if (transferCom) {
        transferCom.$children['0']._data.query = '';
        transferCom.$children['3']._data.query = '';
      }
      this.showStudentsDialog = false;
    },
    handleChange (data) {
      data.forEach((item, index) => {
        this.$set(this.studentsNoid, index, item);
      })
      // this.saveStudent()
      // this.getNowStu()
      // console.log(this.studentsNoid);
    },
    clkBtnDelete (row) {

      this.$confirm('您确信要删除该记录吗', "提示").then(() => {

        let url1 = this.settings.apiUrl + '/classes/delete';
        let d1 = { noid: row.noid };
        request.post(url1, d1).then((d1r) => {
          if (d1r.code === 0) {
            this.getList();
            this.$message('您删除成功了。');
          } else {
            this.$alert('删除学生失败：' + d1r.msg, '提示', {
              type: 'warning'
            });
          }
        }).catch(err => {
          this.loading = false;
          console.log(err);
        });

      })


    },

    clkBtnSave () {
      let url1 = this.settings.apiUrl + '/classes/save';
      this.addOrEdit === 'add' ? this.classes.class_state = 1 : this.classes.class_state = this.classes.class_state
      let d1 = this.classes;
      // console.log(d1);
      request.post(url1, d1).then((d1r) => {
        if (d1r.code === 0) {
          this.getPage();
          this.showSaveteClassesDialog = false;
          if (this.addOrEdit === 'add') {
            const h = this.$createElement;
            this.$msgbox({
              title: '本班验证码',
              message: h('p', null, [
                h('p', { style: 'text-align: center' }, d1r.data.class_code)
              ]),
              showCancelButton: false,
            })
          }
        }
      })


    },
    chgCurrPage (val) {
      this.classesPage.pageNum = val;
      this.getPage();
    },
    getPage () {
      this.getList();
    },
    closeCard () {
      this.showStudentsDialog = false
    },
    tongyi (item) {
      let url1 = this.settings.apiUrl + '/classes/isUserInfoApplyJoinClass';
      let d1 = {
        noid: item.noid,
        studetn_id: item.student_id,
        class_id: item.classes_id,
        is_join_class: 1
      }
      request.post(url1, d1).then((d1r) => {
        this.clkBtnShowAddStudent(this.classRow)
      })
    },
    jujue (item) {
      let url1 = this.settings.apiUrl + '/classes/isUserInfoApplyJoinClass';
      let d1 = {
        noid: item.noid,
        studetn_id: item.student_id,
        class_id: item.classes_id,
        is_join_class: 2
      }
      request.post(url1, d1).then((d1r) => {
        this.clkBtnShowAddStudent(this.classRow)
      })
    }

  },
  clkCreateUser () {
    console.log('alert')
  },
  filters: {
    filterState (srcVal) {
      if (srcVal == 1) {
        return '在授';
      }
      if (srcVal == 0) {
        return '结业';
      }
      return '未知';
    }
  }


};
</script>

<style lang="scss" scoped="scoped">
.box-main2 {
  height: 100%;
  background-repeat: no-repeat;
  background-size: cover;
}

.box-header2 {
  height: 30px;
  background-color: #eceeef;
  padding-left: 20px;
  padding-top: 8px;
}

.box-search2 {
  display: flex;
}
.box-page2 {
  display: flex;
  justify-content: flex-end;
}

.box-search2 {
  padding-bottom: 10px;
  .box-input2 {
    padding-right: 10px;
  }
}
.box-card {
  width: 500px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
}
.box-card .item {
  display: flex;
  align-items: center;
  padding: 10px 0;
}
.box-card .item div {
  flex: 1;
  font-size: 14px;
}
</style>
